package com.example.easynote;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import java.util.List;

import java.util.Random;

import BUS.NotesBUS;
import BUS.paintBUS;
import BUS.picturesBUS;
import DAO.NotesDAO;
import DAO.paintDAO;
import DAO.picturesDAO;
import DTO.paintDTO;
import DTO.picturesDTO;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;

import android.widget.ArrayAdapter;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView.BufferType;
import android.widget.Toast;

import com.easynote.UI.GetImageThumbnail;
import com.easynote.UI.IconContextMenu;
import com.easynote.UI.LineEdittext;

@SuppressLint("SimpleDateFormat")
public class CreateNote extends Activity implements OnClickListener {
	private static final int RESULT_PAINT = 500;
	Button btn_save, btn_camera, btn_indam, btn_inNghien, btn_gachChan,
			btn_clock, btn_option, btn_paint;
	Button btnShare;
	EditText tieuDe;
	TableRow tbrow;
	LinearLayout layoutImage;
	// GridView
	View rootView;
	// GridView gridView;
	ArrayAdapter<Drawable> list;

	int indam = 0, in_Nghien = 0, gachChan = 0;
	Context context;
	LineEdittext edtNoiDung;
	int temp = 0;
	String uri = null;
	// paint
	LinearLayout mL = null;
	boolean mIsDrawing = false;
	int isave = 0;

	private static int ALARM_REQUEST = 300;

	private final int CONTEXT_MENU_ID = 1;
	private IconContextMenu ContextMenuClock = null;
	private IconContextMenu ContextMenuOption = null;
	private final int MENU_ITEM_1_ACTION = 1;
	private final int MENU_ITEM_2_ACTION = 2;
	private final int MENU_ITEM_3_ACTION = 3;

	List<Uri> listUri = new ArrayList<Uri>();
	int count1 = 0;
	int index = 0;
	List<LayoutParams> listParams = new ArrayList<LayoutParams>();
	Uri outputFileUri;
	final int TAKE_PHOTO_CODE = 0;
	Intent cameraIntent;
	EditText editTieuDe;
	private Long mRowId;

	private ArrayList<String> listPic = new ArrayList<String>();
	private ArrayList<String> listPaint = new ArrayList<String>();

	ArrayList<View> viewImage = new ArrayList<View>();
	int counti;

	private String urlFolder = Environment.getExternalStorageDirectory()
			.toString() + "/EasyNotes/temps";
	private String urlUri;
	
	private Cursor mNotesCursor;
	// Notes note = new Notes();
	@SuppressLint("ResourceAsColor")
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_note);

		context = getApplicationContext();

		btn_save = (Button) findViewById(R.id.btn_save);
		btn_camera = (Button) findViewById(R.id.btn_camera);
		btn_indam = (Button) findViewById(R.id.btn_formatB);
		btn_inNghien = (Button) findViewById(R.id.btn_formatI);
		btn_gachChan = (Button) findViewById(R.id.btn_formatU);
		btn_clock = (Button) findViewById(R.id.btn_clock);
		// btn_option = (Button)findViewById(R.id.btn_option);
		layoutImage = (LinearLayout) findViewById(R.id.scrollImage);
		btn_paint = (Button) findViewById(R.id.btn_paint);

		// gridView.setAdapter(new ImageAdapter(this, list));
		btnShare = (Button) findViewById(R.id.btnShare);

		btn_save.setOnClickListener(this);

		btnShare.setOnClickListener(this);
		btn_save.setOnClickListener(this);

		btn_clock.setOnClickListener(this);

		ImageView view = new ImageView(this);
		view.setBackgroundResource(R.drawable.ic_calender);

		tieuDe = (EditText) findViewById(R.id.edt_tieude);
		edtNoiDung = (LineEdittext) findViewById(R.id.txtNoteNames);

		editTieuDe = (EditText) findViewById(R.id.edt_tieude);
		edtNoiDung = (LineEdittext) findViewById(R.id.txtNoteNames);

		registerForContextMenu(btn_clock);

		final String textB = "<b>B</b>";
		btn_indam.setText(Html.fromHtml(textB));
		String textI = "<i>i</i>";
		btn_inNghien.setText(Html.fromHtml(textI));
		String textU = "<u>U</u>";
		btn_gachChan.setText(Html.fromHtml(textU));
		tbrow = (TableRow) findViewById(R.id.tbrow);

		btn_indam.setOnClickListener(new OnClickListener() {
			@Override
			@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
			@SuppressLint("NewApi")
			public void onClick(View arg0) {
				if (indam == 1) {
					btn_indam.setBackground(context.getResources().getDrawable(
							R.color.blue));
					indam = 0;
					tieuDe.setTypeface(null, Typeface.NORMAL);
				} else {
					btn_indam.setBackground(context.getResources().getDrawable(
							R.color.bluetext));
					indam = 1;
					tieuDe.setTypeface(null, Typeface.BOLD);
				}
				temp = 1;
			}
		});

		btn_inNghien.setOnClickListener(new OnClickListener() {
			@Override
			@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
			@SuppressLint("NewApi")
			public void onClick(View arg0) {
				if (in_Nghien == 1) {
					btn_inNghien.setBackground(getResources().getDrawable(
							R.color.blue));
					in_Nghien = 0;

				} else {
					btn_inNghien.setBackground(getResources().getDrawable(
							R.color.bluetext));
					in_Nghien = 1;

				}
			}
		});

		btn_gachChan.setOnClickListener(new OnClickListener() {
			@Override
			@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
			@SuppressLint("NewApi")
			public void onClick(View arg0) {
				if (gachChan == 1) {
					btn_gachChan.setBackground(getResources().getDrawable(
							R.color.blue));
					gachChan = 0;

				} else {
					btn_gachChan.setBackground(getResources().getDrawable(
							R.color.bluetext));
					gachChan = 1;

				}
			}

		});

		Resources res = getResources();
		// arguments: groupId, optionId, order, title
		ContextMenuClock = new IconContextMenu(this, CONTEXT_MENU_ID);
		ContextMenuClock.addItem(res, "Lấy th�?i gian hiện tại",
				R.drawable.ic_calender, MENU_ITEM_1_ACTION);
		ContextMenuClock.addItem(res, "Đặt lời nhắc", R.drawable.ic_add,
				MENU_ITEM_2_ACTION);
		ContextMenuClock.addItem(res, "Xóa l�?i nhắc", R.drawable.ic_close,
				MENU_ITEM_3_ACTION);

		ContextMenuClock
				.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
					@Override
					public void onClick(int menuId) {

						switch (menuId) {
						case MENU_ITEM_1_ACTION:

						{

							/*
							 * Time today = new Time(Time.getCurrentTimezone());
							 * today.setToNow(); String currentTime =
							 * today.monthDay+"/" + today.month +"/"+ today.year
							 * + "-" + today.hour +":"+today.minute + ":" +
							 * today.second;
							 */
							String datetime = null;
							SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
							try {
								Date date = new Date();
								datetime = dformat.format(date);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							editTieuDe.setText(datetime + " _ " + editTieuDe.getText().toString());
							
							break;
						}

						case MENU_ITEM_2_ACTION:

						{

							Intent myAlarm = new Intent(getApplicationContext(), Alarm.class);
							myAlarm.putExtra(NotesDAO.KEY_ROWID, mRowId);
							myAlarm.putExtra(NotesDAO.KEY_TITLE, editTieuDe.getText()
									.toString());
							myAlarm.putExtra(NotesDAO.KEY_BODY, edtNoiDung.getText().toString());
							startActivityForResult(myAlarm, ALARM_REQUEST);
							// showDialog(CONTEXT_MENU_ID);
							break;
						}

						case MENU_ITEM_3_ACTION:
							Toast.makeText(getApplicationContext(),
									"You've clicked on menu item 3",
									Toast.LENGTH_LONG).show();
							break;
						default:
							break;
						}

					}
				});

		btn_camera.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Random generator = new Random();
				int n = 10000;
				n = generator.nextInt(n);
				// ArrayList<picturesDTO> listpicture = picturesDAO.getAllPic();
				// int stt = listpicture.size();
				String name = "pic" + n + ".jpg";
				
				listPic.add("pic" + n + ".jpg");
				
				File path = new File(urlFolder);
				if(!path.exists())
					path.mkdirs();
				
				File newfile = new File(path,name);
				
				try {
					newfile.createNewFile();
				} catch (IOException e) {
				}

				outputFileUri = Uri.fromFile(newfile);
				// listPic.add(file);
				cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

				startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
			}

		});

		btn_paint.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent PaintIntent = new Intent(getApplicationContext(),
						NoteWithPaint.class);
				PaintIntent.putExtra("url", urlFolder);
				startActivityForResult(PaintIntent, RESULT_PAINT);
			}
		});

		// Lấy dữ liệu từ Easy Note
		// Main//////////////////////////////////////////////////////////////////////
		mRowId = null;
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			NotesDAO.open(this);
			picturesDAO.open(this);
			paintDAO.open(this);
			
			mNotesCursor = NotesBUS.fetchAllNotes();
			
			//String title = extras.getString(NotesDAO.KEY_TITLE);
			//String body = extras.getString(NotesDAO.KEY_BODY);
			mRowId = extras.getLong(NotesDAO.KEY_ROWID);
			//urlFolder = extras.getString(NotesDAO.KEY_URLFOLDER);

			///////////
			int vitri = extras.getInt("vitri");
			Cursor c = mNotesCursor;
			c.moveToPosition(vitri);
			String title = c.getString(c.getColumnIndexOrThrow(NotesDAO.KEY_TITLE));
			String body = c.getString(c.getColumnIndexOrThrow(NotesDAO.KEY_BODY));
			
			urlFolder = c.getString(c.getColumnIndexOrThrow(NotesDAO.KEY_URLFOLDER));
			///////////
			ArrayList<String> listPic1 = new ArrayList<String>();
			ArrayList<String> listPaint1 = new ArrayList<String>();
			
			//listPic1 = extras.getStringArrayList("ListPic");
			//listPaint1 = extras.getStringArrayList("ListPaint");

			
			//////////
			ArrayList<picturesDTO> dto = picturesBUS.getAllPicfromNote(mRowId); // id
			// pictures
			ArrayList<paintDTO> paintdto = paintBUS.getAllPaintfromNote(mRowId);
			
			for (int j = 0; j < dto.size(); j++) {
				String temp = dto.get(j).getUrlPic();
				listPic1.add(temp);
			}
			for (int j = 0; j < paintdto.size(); j++) {
				String temp1 = paintdto.get(j).getUrlPaint();
				listPaint1.add(temp1);
			}
			//////////
			body = body.replace("\n", "");
			Log.i("body",body);
			
			if(urlFolder != null)
			{
				File temp = new File(urlFolder);
				Uri uri = Uri.fromFile(temp);
				urlUri = uri.toString();
			}
			if (title != null) {
				editTieuDe.setText(title);
				
			}
			if (body != null) {
				edtNoiDung.setText(body);
			}

			if (listPic1 != null) {
				// SpannableStringBuilder ss2 = null;
				for (int i = 0; i < listPic1.size(); i++) {
					Log.i("Pic of note", listPic1.get(i));
					Bitmap bitmap = null;
					try {
						bitmap = MediaStore.Images.Media.getBitmap(
								getContentResolver(),
								Uri.parse(urlUri + "/"
										+ listPic1.get(i).toString()));
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// Drawable drawable = new BitmapDrawable(bitmap);
					// edtNoiDung.setCompoundDrawables(null, drawable, null,
					// null);
					Editable editable = edtNoiDung.getEditableText();
					editable.insert(editable.length(), "\n" + " " + "\n");
					// SpannableStringBuilder ss2 = new
					// SpannableStringBuilder(charSeq+" ");
					Drawable d2 = new BitmapDrawable(bitmap);
					d2.setBounds(0, 0, d2.getIntrinsicWidth(),
							d2.getIntrinsicHeight());

					//ImageSpan span2 = new ImageSpan(d2,
							//ImageSpan.ALIGN_BASELINE);
					
					ImageSpan span2 = new ImageSpan(d2, ImageSpan.ALIGN_BOTTOM);
					editable.setSpan(span2, editable.length() - 2,
							editable.length() - 1,
							Spannable.SPAN_INCLUSIVE_INCLUSIVE);

					edtNoiDung.setText(editable, BufferType.SPANNABLE);
					// CharSequence txt = edtNoiDung.getText();
					// edtNoiDung.setText(txt);

				}

				// edtNoiDung.setEnabled(false);
			}
			if (listPaint1 != null) {

				// SpannableStringBuilder ss2;
				for (int i = 0; i < listPaint1.size(); i++) {

					Log.i("Pic of note", listPaint1.get(i));
					Bitmap bitmap = null;
					try {
						bitmap = MediaStore.Images.Media.getBitmap(
								getContentResolver(),
								Uri.parse(urlUri + "/"
										+ listPaint1.get(i).toString()));
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					// CharSequence charSeq= edtNoiDung.getText();
					Editable editable = edtNoiDung.getEditableText();
					editable.insert(editable.length(), "\n" + " " + "\n");
					// SpannableStringBuilder ss2 = new
					// SpannableStringBuilder(charSeq+" ");
					Drawable d2 = new BitmapDrawable(bitmap);
					d2.setBounds(0, 0, 400, 400);

					ImageSpan span2 = new ImageSpan(d2, ImageSpan.ALIGN_BOTTOM);

					editable.setSpan(span2, editable.length() - 2,
							editable.length() - 1,
							Spannable.SPAN_INCLUSIVE_INCLUSIVE);

					edtNoiDung.setText(editable, BufferType.SPANNABLE);
					
				}

				// edtNoiDung.setEnabled(false);
			}

		}
		counti = layoutImage.getChildCount();
		for (int i = 0; i < counti; i++) {
			viewImage.toArray()[i] = layoutImage.getChildAt(i);
		}

		layoutImage.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				for (int i = 0; i < counti; i++) {
					if (v == layoutImage.getChildAt(i)) {
						Log.i("click", "lick");
						Intent intent = new Intent();
						intent.setAction(android.content.Intent.ACTION_VIEW);

						// String introURI = "file:///sdcard/"+".mp3";
						intent.setDataAndType(
								Uri.parse(listUri.toArray()[i].toString()),
								"image/*");
						startActivity(intent);
					}
				}

			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	@SuppressLint("NewApi")
	protected Dialog onCreateDialog(int id) {
		if (id == CONTEXT_MENU_ID) {
			AlertDialog dialog;
			dialog = (AlertDialog) ContextMenuClock.createMenu("");
			dialog.getListView().setBackground(
					getResources().getDrawable(R.color.colorDialog));

			return dialog;
		} else
			return super.onCreateDialog(id);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		return applyMenuOption(item);
	}

	public boolean applyMenuOption(MenuItem item) {
		return false;
	}

	// xử lý ảnh từ camera
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {

			switch (requestCode) {

			case TAKE_PHOTO_CODE: {
				if (resultCode == RESULT_OK) {

					Bitmap bitmap = null;
					try {

						GetImageThumbnail getImageThumbnail = new GetImageThumbnail();
						bitmap = getImageThumbnail.getThumbnail(outputFileUri,
								this);

					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					// Setting image image icon on the imageview

					/*
					 * Drawable drawable = new BitmapDrawable(getResources(),
					 * bitmap); try { list.add(drawable); } catch(Exception e)
					 * {}
					 * 
					 * try { gridView.setAdapter(new ImageAdapter(this, list));
					 * } catch(Exception e) {
					 * Toast.makeText(this.getApplicationContext(), "fail",
					 * 1).show(); }
					 */
					ImageView view = new ImageView(this);
					view.setImageBitmap(bitmap);
					layoutImage.addView(view);
					break;
				}
			}
			case RESULT_PAINT: {
				Bundle extras = data.getExtras();
				if (resultCode == RESULT_OK) {
					String uri = extras.getString("paint");
					listPaint.add(extras.getString("name"));

					Uri uriFile = Uri.parse(uri);
					Bitmap bitmap = null;
					try {

						GetImageThumbnail getImageThumbnail = new GetImageThumbnail();
						bitmap = getImageThumbnail.getThumbnail(uriFile,
								CreateNote.this);
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					// test

					ImageView view1 = new ImageView(this);
					view1.setImageBitmap(bitmap);
					layoutImage.addView(view1);
				}
				break;
			}

			}
		} catch (Exception e) {

		}
		;

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.easy_note_main, menu);
		return true;
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

		switch (arg0.getId()) {
		case R.id.btnShare:
			edtNoiDung.setCursorVisible(false);
			edtNoiDung.buildDrawingCache();
			Bitmap bmp = Bitmap.createBitmap(edtNoiDung.getDrawingCache());

			File myDir = new File(Environment.getExternalStorageDirectory()
					.toString() + "/easynote/merge_image");
			
			if(!myDir.exists())
				myDir.mkdirs();
			Random generator = new Random();
			int n = 10000;
			n = generator.nextInt(n);
			String fname = "Image-" + n + ".jpg";
			File file = new File(myDir, fname);
			if (file.exists())
				file.delete();
			try {
				FileOutputStream out = new FileOutputStream(file);
				Bitmap originalBitmap = Bitmap.createBitmap(bmp.getWidth(),
						bmp.getHeight(), Bitmap.Config.ARGB_8888);

				Canvas canvas = new Canvas(originalBitmap);

				Paint paint = new Paint();
				paint.setColor(Color.BLUE);// WHITE); // Text Color
				paint.setStrokeWidth(40); // Text Size
				paint.setXfermode(new PorterDuffXfermode(
						PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern
				// some more settings...
				canvas.drawBitmap(BitmapFactory.decodeResource(
						CreateNote.this.getResources(), R.drawable.white), 0,
						0, paint);

				canvas.drawBitmap(bmp, 0, 0, paint);

				originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
				Log.i("Saveimage", "Save Sucessfully");
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			// image.setImageBitmap(bmp);
			Uri uri = Uri.fromFile(file);
			edtNoiDung.setCursorVisible(true);
			Intent intent = new Intent(CreateNote.this, ConnectFacebook.class);
			intent.putExtra("dir", uri.toString());
			startActivity(intent);
			/*
			 * Intent viewImage = new Intent();
			 * viewImage.setAction(android.content.Intent.ACTION_VIEW);
			 * viewImage.setDataAndType(Uri.fromFile(file), "image/png");
			 * startActivity(viewImage);
			 */

			break;
		case R.id.btn_clock:

			showDialog(CONTEXT_MENU_ID);
			break;
		case R.id.btn_save: {
			// luu note xuong sqlite
			// ve man hinh quan ly ds ghi chu
			String tieuDe = editTieuDe.getText().toString();
			String datetime = null;
			SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try {
				Date date = new Date();
				datetime = dformat.format(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			Bundle bundle = new Bundle();

			bundle.putString(NotesDAO.KEY_TITLE, editTieuDe.getText()
					.toString());
			bundle.putString(NotesDAO.KEY_BODY, edtNoiDung.getText().toString());
			bundle.putString(NotesDAO.KEY_DATE, datetime);
			bundle.putString(NotesDAO.KEY_URLFOLDER, urlFolder);

			bundle.putStringArrayList("ListPic", listPic);
			bundle.putStringArrayList("ListPaint", listPaint);

			Log.i("DATE TIME", datetime);

			if (mRowId != null) {
				bundle.putLong(NotesDAO.KEY_ROWID, mRowId);
			}

			Intent mIntent = new Intent();
			mIntent.putExtras(bundle);
			setResult(RESULT_OK, mIntent);
			finish();
			}
		break;
		}}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	}
	
}
